// JavaScript Document

$(document).ready( function() {
    feedback.init();
});

var feedback = {
    lastMsg: null,
    lastCategoryLink: null,

    // initialise the feedback object
    init: function() {
		
        // register the cmb selector
        $p.addEvent("fbcat_cmb", "change", function() {
            if( this.value == "add_cat" ) {
				
            } else {
                feedback.loadMessagesInCategory( this.value );
            }
        });
		
        // register the select all event
        $p.addEvent("checker", "click", function() {
			
            var checked = this.checked;
            $p.all("#msg_list_content input[type=checkbox]", function(el) {
                el.checked = checked;
            });
        });
		
        // register the event listener for the delete link
        $p.addEvent("unread-link", "click", function() {
            feedback.processMessages('mark_unread');
        });

        // create a UI Menu using the UI script framework
        var items_array = new Array();
        $p.all(".category-list li a", function(el, i) {
            var mi = {
                id: el.id,
                name: el.innerHTML,
                title: el.title,

                // menus will call this action and supply the menu item as a parameter, so define the
                // action to use the supplied object
                action: function(mi) {
                    feedback.moveMessagesToCategory( mi );
                }
            };

            items_array[i] = mi;
        });

        ui.menu( $p.$("#move-link"), {
            items: items_array
        });

        // create a UI Menu using the UI Script framework for the Actions Menu
        var actions_array = [{
            id: "mark_read",
            name: "Mark as Read",
            title: "Mark Selected Messages As Read",
            action: function(mi) {
                feedback.processMessages( mi.id );
            }
        },{
            id: "mark_unread",
            name: "Mark as Unread",
            title: "Mark Selected Messages As Unread",
            action: function(mi) {
                feedback.processMessages( mi.id );
            }
        }];

        ui.menu( $p.$("#actions-link"), {
            items: actions_array
        });
		
        // register the event listener for the delete link
        $p.addEvent("delete-link", "click", function() {
            feedback.processMessages('delete');
        });
		
        // adjust the UI location of the add category dialog
        var dialog = $p.$("#cat-add-dialog");
        dialog.style.left = "130px";
        dialog.style.top = "30px";
		
        // register the event listener for the add category link
        $p.addEvent('add-cat-link', 'click', function() {
            feedback.showDialogForAdd();
        });
		
        // register the event listener for the add category link
        $p.addEvent('edit-cat-link', 'click', function() {
            feedback._showDialogForEdit();
        });
		
        // register the event listener for the delete category link
        $p.addEvent('del-cat-link', 'click', function() {
            feedback.deleteFeedbackCategory();
        });
		
        // register the event listener for the cat cancel button
        $p.addEvent('cat-cancel-btn', 'click', function() {
            document.getElementById("cat-add-form").reset();
            $p.hide('cat-add-dialog');
        });
		
        // register the event listener for all the category links
        $p.all(".category-list li a", function(el) {
            el.onclick = function() {
                //clear any previously selected list items
                $p.all(".category-list li", function(li) {
                    li.className = '';
                });
				
                // load the articles in this category and indicate it as selected
                feedback.loadMessagesInCategory( this );
				
                return false;
            };
        });
		
		
        // load the initial list of items
        var firstCat = $p.$(".category-list li:first-child a");
        feedback.loadMessagesInCategory( firstCat );
    },

    loadMessagesInCategory: function(catLink) {
	
        var catName = catLink.innerHTML;
        var catId = catLink.id;
		
        // check if the catLink parent exists before calling this, since could
        // be called with a catLink which may have already been removed from the DOM
        if( catLink.parentNode != null ) {
            catLink.parentNode.className = 'selected';
        }
		
        // cache the link information for later
        feedback.lastCategoryLink = catLink;
		
        // update the article list header
        $p.$(".articles-pane .pane-header").innerHTML = 'Messages In ' + catName;
		
        var query = "action=load_messages&cat=" + catId;
        $p.post("ajax_pages/feedback_msg.php",query, function(data) {
			
			$p("#msg_list_content").html(data);
						  
            $p.all("#msg_list_content .message-link", function(el) {
                el.onclick = function() {
                    feedback.loadMessage( this.id );
                    return false;
                };
            });
        });
    },

    loadMessage: function(id) {

        // create a simple array to hold the selected message for processing
        var selected = new Array();
		
        // if a previous message has been selected, unselect by indicating it as read
        if( feedback.lastMsg != null ) {
            selected[0] = feedback.lastMsg;
            feedback.markMessages(selected,"read");
        }
		
        // cache the currently selected message id
        feedback.lastMsg = id;
		
        // select the clicked message
        selected[0] = id;
        feedback.markMessages(selected, "selected");
		
        var query = "id=" + id;
        $p.get("ajax_pages/feedback_msg.php",query, function(data) {
			$p("#msg_pane").html(data);
		});
    },

    moveMessagesToCategory: function(menuLink) {
        var selected = feedback.getCheckedMessages();

        if( selected.length == 0 ) {
            alert("Please Select Messages To Be Moved");
            return;
        }

        var msg_ids = "";
        for(var i = 0; i < selected.length; i++) {
            msg_ids += selected[i];

            if( i < selected.length - 1 ) {
                msg_ids += ",";
            }
        }

        var query = "action=move_messages&category_id=" + menuLink.id + "&msg_ids=" + msg_ids;

        
        $p.setLoaderMessage("Moving Selected Messages To <b>" + menuLink.innerHTML + "</b>");
        $p.post("ajax_pages/feedback_msg.php", query, function(data) {
			$p("#msg_pane").html(data);
            feedback.removeMessages( feedback.getCheckedMessages() );
        });
    },
	
    showDialogForAdd: function() {
        $p('#cat-add-dialog .cms-dialog-title').html("Add Category");
        $p('#cat-add-btn').val('Add Category');
        $p('#cat-add-btn').node().onclick = function() {
            feedback.addFeedbackCategory();
        };
        $p('#cat-add-dialog').show();
    },
	
    _showDialogForEdit: function() {
        var selected = feedback.lastCategoryLink;
        var query = "action=load_category&category_id=" + selected.id;
        $p.post('ajax_pages/feedback_msg.php',query, function(data) {
            if(JSON) {
				
                var obj = JSON.parse(data);

                document.getElementById("CategoryName").value = obj.CategoryName;
                document.getElementById("CategoryDesc").value = obj.CategoryDesc;
                document.getElementById("CategoryTag").value = obj.CategoryTag;
                document.getElementById("FwdToEmail").value = obj.FwdToEmail;
                document.getElementById("FwdEmail").value = obj.FwdEmail;
				
                $p.$('#cat-add-dialog .cms-dialog-title').innerHTML = "Edit Category Information";
                $p.$('#cat-add-btn').value = 'Save Changes';
                $p.$('#cat-add-btn').onclick = function() {
                    feedback.updateFeedbackCategory();
                };
                $p.show('cat-add-dialog');
            }
        });
    },
	
    addFeedbackCategory: function() {
		
		var valid = $p("#cat-add-form").validate({
            "CategoryName": "Category Name",
            "CategoryDesc": "Category Description",
            "CategoryTag": "Category Tag"
        });
		
        if( !valid ) {
            return;
        }
		
        var query = "action=add_category&" + $p("#cat-add-form").serialize();
        $p.post("ajax_pages/feedback_msg.php", query, function(data) {
			
            if(JSON) {
                var obj = JSON.parse(data);

                var a = document.createElement("a");
                a.id = obj.category_id;
                a.title = obj.category_desc;
                a.setAttribute("href","#");
                a.innerHTML = obj.category_name;
                a.onclick = function() {
                    //clear any previously selected list items
                    $p.all(".category-list li", function(li) {
                        li.className = '';
                    });
					
                    // load the articles in this category and indicate it as selected
                    feedback.loadMessagesInCategory( this );
					
                    return false;
                };
				
                var li = document.createElement("li");
                li.appendChild(a);
				
                $p.$(".category-list").appendChild(li);
			
            // if JSON does not exist natively, simply refresh the page and load the
            // categories from the database
            } else {
                history.go(0);
            }
			
            document.getElementById("cat-add-form").reset();
            $p('#cat-add-dialog').hide();
        });
    },
	
    updateFeedbackCategory: function() {
        var valid = $p("#cat-add-form").validate({
            "CategoryName": "Category Name",
            "CategoryDesc": "Category Description",
            "CategoryTag": "Category Tag"
        });
		
        if( !valid ) {
            return;
        }
		
        var lastCat = feedback.lastCategoryLink;
        var query = "action=update_category&category_id=" + lastCat.id + "&" + $p("#cat-add-form").serialize();
        $p.post("ajax_pages/feedback_msg.php", query, function(data) {

            // retrieve the menu object information and update the link information
            // incase the titles or descriptions have been changed
            if(JSON) {
				
                var obj = JSON.parse(data);
                lastCat = feedback.lastCategoryLink;
                lastCat.title = obj.category_desc;
                lastCat.innerHTML = obj.category_name;

            } else {
                history.go(0);
            }

            document.getElementById("cat-add-form").reset();
            $p('#cat-add-dialog').hide();
        });
    },
	
    deleteFeedbackCategory: function() {
        var lastCat = feedback.lastCategoryLink;
		
        $p.showConfirmMessage({
            title: "Confirm Feedback Category Delete",
            content: "This will delete the the <b>" + lastCat.innerHTML + "</b> category and all messages in it. "
            + "Do you want to continue this action?",
					
            okButtonText: "Delete Category",
            okButtonAction: function() {
                var query = "action=delete_category&category_id=" + feedback.lastCategoryLink.id ;
                $p.post('ajax_pages/feedback_msg.php', query, function() {
                    feedback.lastCategoryLink.parentNode.removeChild( feedback.lastCategoryLink );
                    feedback.loadMessagesInCategory( feedback.lastCategoryLink );
                });
            }
        });
    },
	
    markMsgAsUnread: function() {
        document.getElementById("msg-row-" + feedback.lastMsg).className = "msgread";
    },
	
    /**
	 * Marks the selected messages as unread
	 */ 
    markMsgAsSelected: function() {
        document.getElementById("msg-row-" + feedback.lastMsg).className = "msgselected";
    },
	
    /**
	 * Returns the database ID of the last message that was selected to be read
	 * by the user.
	 */
    getLastSelectedMessageID: function() {
        return feedback.lastMsg;
    },
	
    // selects or unselects all the messages in the message list pane
    selectAllMessages: function(state) {
        var mlc = document.getElementById("msg_list_content");
		
        if( mlc != null ) {
            var msgs = mlc.getElementsByTagName("input");
			
            for(var i = 0; i < msgs.length; i++ ) {
                msgs[i].checked = state;
            }
        }
    },
	
    /**
     * Returns a list of message IDs of the messages that have been checked for
     * processing
     */
    getCheckedMessages: function() {
        var mlc = document.getElementById("msg_list_content");
        var msgs = mlc.getElementsByTagName("input");
        var selected = new Array();
        var checkbox = null;
		
        for( var i = 0, j = 0; i < msgs.length; i++ ) {
            checkbox = msgs[i];
            if( checkbox != null && checkbox.checked ) {
                selected[j++] = checkbox.value;
            }
        }
		
        return selected;
    },
	
    /**
     * Prepares the data about the selected messages and sends them to
     * the server for processing
     */ 
    processMessages: function(action) {
        // if no action has been specified, simply exit
        if( action == "" ) {
            return;
        }
		
        var selected = feedback.getCheckedMessages();
		
        if( selected.length == 0 ) {
            alert("No Messages Have Been Selected. Please Select Messages To Process!");
            return;
        }
		
        if( action == "delete" ) {
            if( !confirm("Do you want to delete the selected messages?") ) {
                return;
            }
        }
		
        var msgs = "";
        for(var i = 0; i < selected.length; i++) {
            msgs += selected[i];
			
            if( i < selected.length - 1 ) {
                msgs += "|";
            }
        }
		
        var query = "action=" + action + "&msgs=" + msgs;
        query = encodeURI(query);
        $p.post("ajax_pages/feedback_msg.php",query, function(data) {
			$p("#msg_pane").html(data);
            feedback.processMessagesCallback(action, selected);
        });
    },
	
    /**
	 * A Callback method for the processMessages function
	 */
    processMessagesCallback: function(action, selected) {
		
        if( action == "delete" ) {
            feedback.removeMessages(selected);
        } else if( action == "mark_unread" ) {
            feedback.markMessages(selected, "unread");
        } else if( action == "mark_read" ) {
            feedback.markMessages(selected, "read");
        }
    },
	
    /**
	 * Marks the selected messages as either read or unread
	 */
    markMessages: function(messages, mark) {
        if( messages == null ) {
            return;
        }
		
        var msg = null;
		
        for( var i = 0; i < messages.length; i++ ){
            msg = document.getElementById("msg-row-" + messages[i] );
			
            if( msg == null ) continue;
			
            msg.className = "msg" + mark;
        }
    },
	
    /**
     * Removes the specified messages from the display
     */
    removeMessages: function(messages) {
        if( messages == null ) {
            return;
        }
		
        var msg = null;
        var msglist = document.getElementById("msg_list_table");
		
        for( var i = 0; i < messages.length; i++ ) {
            msg = document.getElementById("msg-row-" + messages[i] );
			
            if( msg != null ) {
                msg.parentNode.removeChild(msg);
            }
        }
    }
};